/*
 * signalisationClient.c
 *
 *  Created on: 25 mars 2010
 *      Author: kamkoum
 */
#include "signalisation_client.h"


/**
 * handling the server response

return_t handler_cmd_response(char* buf,int sock){
	char * cmd;
	//sscanf(get_cmd(buf), "%s", cmd);
	cmd = strtok(buf," ");
	printf("Commande envoyee: %s \n ",cmd);
	if (strcmp(cmd, "list")) {
		//cmd_list_handler(sock);
		return RT_OK;
	} else if ((strcmp(cmd, "file"))==0) {
		//cmd file response
		//cmd_file_handler(sock);
		return RT_OK;
	} else if (strcmp(cmd, "get")) {
		char name[NAMESIZE];
		sscanf(buf, "%s %s", cmd, name);
		//recv_get_cmd(name, sock);
		//creation dune socket a partir du num de port envoye par le serveur
		recv_msg(fpath(name,DIR_FILES_CLIENT),sockdata);
		return RT_OK;
	} else if (strcmp(cmd, "traffic")) {
		return RT_OK;
	} else if ((strcmp(cmd, "ready"))==0) {
		return RT_OK;
	} else if (strcmp(cmd, "checksum")) {
		return RT_OK;
	} else if (strcmp(cmd, "neighbourhood")) {
		cmd_neighbourhood_request();
		return RT_OK;
		//	} else if (strcmp(cmd, "neighbour")) {
		//		return RT_OK;
	} else if (strcmp(cmd, "redirect")) {
		return RT_OK;
	} else if (strcmp(cmd, "error")) {
		return RT_OK;
	}
	printf("cmd not find see user manually\n");
	return RT_ERR;
}
*/
/**
 * handling a response of a file cmd
 */
/*
head* recv_fileHeader(int sock){
	head *headOfFile = malloc(sizeof(head));
	if((recv(sock, headOfFile, sizeof(head), 0))==-1)
		perror("receive");
	else{
		if(headOfFile==NULL){
			printf("Erreur reception file Header\n");

		}
		else{
			if(headOfFile->exist==1){
				printf("size of file : %\n",headOfFile->taille);
				return headOfFile;
			}
			else{
				printf("File inexistant try command list to get existant files\n");
			}
		}
	}
	return NULL;
}
*/
/**
 * handling a response of a ready cmd
 * also crate a file named fileNameRecived
 */
/*void recv_get_cmd(char *fileName, int sock){
	printf(".1.\n");
	head* headOfFile = recv_fileHeader(sock);
	printf(".2.\n");
	int endOfFile;
	if(headOfFile!const char *pathname=NULL){
		endOfFile = headOfFile->taille;
		char text[BUFSIZE];
		int recived = 0;
		int ret;
		//create a file named fileName+Received
		int fd=open(strcat(fileName,"Received"),O_WRONLY | O_CREAT);
		if(fd==-1){
			perror("open");
		}
		else{
			printf("receiving file ...\n");
			while(recived < endOfFile){
				ret = recv(sock,text,BUFSIZE,0);
				if(ret==-1)
					perror("recv");
				else{
					recived+=ret;
					if((write(fd,text,BUFSIZE))==-1){
						perror("Write");
					}
				}
			}
			printf("file received with success\n");
			close(fd);
		}
	}
}
*/

void cmd_neighbourhood_request(){

}
int recv_msg(const char *pathname,int sock){
	int fd,n;
	char msg[BUFSIZE];
	CHK_ERR((fd=open(pathname,O_WRONLY)),"error open");
	while((n = recv(sock, msg, BUFSIZE, 0)) > 0){
		CHK_ERR(write(fd,msg,BUFSIZE),"error write");

	}
	if(n<0){
		perror("Recv_msg->recv error");
	}

	close(fd);
	return 1;
}
